package com.example.kingdee.jstSync.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.example.kingdee.KingdeeCreate.dto.CreateInDto;
import com.example.kingdee.KingdeeCreate.impl.CreateSalBillImpl;
import com.example.kingdee.block.JuShuiTanBlock;
import com.example.kingdee.common.AjaxResult;
import com.example.kingdee.common.StringUtils;
import com.example.kingdee.common.UUIDUtils;
import com.example.kingdee.config.RuoYiConfig;
import com.example.kingdee.dto.EntryIds;
import com.example.kingdee.dto.PurchaseSyncDto;
import com.example.kingdee.dto.SyncDto;
import com.example.kingdee.entity.*;
import com.example.kingdee.jstSync.JstSyncAbstract;
import com.example.kingdee.jstSync.entity.JstResult;
import com.example.kingdee.kingdeeBridge.common.RequestResult;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import com.example.kingdee.util.JuShuiTanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 云星空预约入库上传实现类
 */
@Service
public class JstAppointMenTinImpl extends JstSyncAbstract {

    @Autowired
    private JuShuiTanBlock juShuiTanBlock;
    @Autowired
    private CreateSalBillImpl createSalBill;
    @Autowired
    private TBxStMapper tBxStMapper;
    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Override
    public int getOrderInfoPage(SyncDto syncDto, PurchaseSyncDto purchaseSyncDtoPage) {
        return JuShuiTanUtil.getOrderInfoPage(purchaseSyncDtoPage, FormIdEnum.purchaseQuery, juShuiTanBlock.getAccessToken());
    }

    @Override
    public JstResult selectJstResult(SyncDto syncDto, PurchaseSyncDto purchaseSyncDto) {
        //处理单据编号
        List<EntryIds> entryIds = syncDto.getEntryIds();
        List<String> poIdsParam = new ArrayList<>();
        for (EntryIds entryId : entryIds) {
            if (entryId.getIsLast().equals("否")){
                poIdsParam.add(entryId.getEntryId());
            }
        }
        syncDto.setPoIds(poIdsParam);
        JstResult jstResult = new JstResult();
        //查询云星空数据
        List<Map<String, Object>> purMapList = tBxStMapper.getPurInfoList(syncDto);
        //构建预约入库数据
        if (purMapList != null && purMapList.size() != 0){
            List<JstAppointMenTin> jstAppointMenTinList = new ArrayList<>();
            for (Map<String, Object> appoint : purMapList) {
                //处理采购单号
                String poId = appoint.get("poId") == null ? "" : appoint.get("poId").toString();
                if (!StringUtils.isEmpty(poId)){
                    List<ItemsItem> items = new ArrayList<>();
                    List<Integer> poIds = new ArrayList<>();
                    poIds.add(Integer.parseInt(poId));
                    JstAppointMenTin jstAppointMenTin = new JstAppointMenTin();
                    jstAppointMenTin.setPoIds(poIds);
                    jstAppointMenTin.setExternalId(UUIDUtils.getId());//外部预约单号
                    jstAppointMenTin.setPlanArriveDate(SqlTool.getNowForString());
                    jstAppointMenTin.setRptEntryId(Integer.parseInt(appoint.get("purEntryId").toString()));
                    jstAppointMenTin.setKingdeeBillNo(appoint.get("purBillNo").toString());
                    //处理商品数据
                    ItemsItem item = new ItemsItem();
                    item.setSkuId(appoint.get("itemNumber").toString());
                    item.setQty(Double.parseDouble(appoint.get("noInStockQty").toString()));
                    items.add(item);
                    jstAppointMenTin.setItems(items);
                    jstAppointMenTinList.add(jstAppointMenTin);
                }
            }
            jstResult.setJstAppointMenTinList(jstAppointMenTinList);
        }
        return jstResult;
    }

    @Override
    public void kingdeeSync(SyncDto syncDto, JstResult jstResult) {
        List<JstAppointMenTin> jstAppointMenTinList = jstResult.getJstAppointMenTinList();
        //普通商品集合
        for (JstAppointMenTin jstAppointMenTin : jstAppointMenTinList) {
            String externalId = jstAppointMenTin.getRptEntryId() == null ? "" : jstAppointMenTin.getRptEntryId().toString();
            List<ItemsItem> itemList = jstAppointMenTin.getItems();
            ArrayList<HashMap<String, Object>> items = new ArrayList<>();
            for (ItemsItem item : itemList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("sku_id", item.getSkuId());
                map.put("qty", item.getQty());
                items.add(map);
            }
            String id = UUIDUtils.getId();
            HashMap<String, Object> jstAppointMenTinObj = new HashMap<>();
            jstAppointMenTinObj.put("po_ids", jstAppointMenTin.getPoIds());
            jstAppointMenTinObj.put("external_id", id);
            jstAppointMenTinObj.put("plan_arrive_date", jstAppointMenTin.getPlanArriveDate());
            jstAppointMenTinObj.put("item_type", "成品");
            jstAppointMenTinObj.put("wms_co_id", jstAppointMenTin.getWmsCoId());
            jstAppointMenTinObj.put("items", items);
            jstAppointMenTinObj.put("is_confirm", true);
            //获取accessToken的地址
            String url = ruoYiConfig.getOpenApiUrl() + FormIdEnum.getDBTableName(FormIdEnum.appointMenInUpload.name());
            String result = JuShuiTanUtil.sendOpenApiHttp(url, jstAppointMenTinObj, juShuiTanBlock.getAccessToken());
            AppointMenTinParam appointMenTinParam = JSONObject.parseObject(result, AppointMenTinParam.class);
            //聚水塘预约入库单号
            Integer poId = appointMenTinParam.getData().getData().getPoId();
            if (appointMenTinParam.getCode() == 0){
                SyncLog syncLog = new SyncLog();
                syncLog.setJstBillno(jstAppointMenTin.getKingdeeBillNo());
                syncLog.setKingdeeBillno(String.valueOf(poId));
                syncLog.setObjectId("0");
                insertSyncLog(syncDto, syncLog, true);
            }else {
                SyncLog syncLog = new SyncLog();
                syncLog.setJstBillno(jstAppointMenTin.getKingdeeBillNo());
                syncLog.setSyncErrorMsg(appointMenTinParam.getMsg());
                syncLog.setObjectId("0");
                insertSyncLog(syncDto, syncLog, false);
            }
        }
    }

    @Override
    protected void insertSyncLog(SyncDto syncDto, SyncLog syncLog, boolean isSucceed) {
        syncLog.setSyncType("预约入库上传");
        syncLog.setSrcBill("金蝶采购单");
        syncLog.setTarBill("聚水潭预约入库单");
        syncLog.setSyncTime(SqlTool.getNowForString());
        syncLog.setSyncUser(syncDto.getUserName() == null ? "系统自动同步" : syncDto.getUserName());
        if (isSucceed){
            syncLog.setSyncResult("同步成功");
            syncLog.setSyncErrorMsg("无");
        }else {
            syncLog.setIsDispose("未处理");
            syncLog.setSyncResult("同步失败");
        }
        tBxStMapper.insertSyncLog(syncLog);
    }
}
